#include "DataBaseAccessor.hpp"

#include <QDebug>
#include <QCryptographicHash>
#include <QSqlQuery>
#include <QSqlError>
#include <QSqlRecord>

DataBaseAccessor* DataBaseAccessor::m_instance(nullptr);

DataBaseAccessor* DataBaseAccessor::instance()
{
    if(m_instance)
        return m_instance;
    return m_instance = new DataBaseAccessor();
}

bool DataBaseAccessor::connect(QString &hostName, QString &dbName,
                               QString &userName, QString &userPassword)
{
    if (m_db.isOpen()) {
        qDebug() << "Connection has already exists";
        return false;
    }

    m_db = QSqlDatabase::addDatabase("QMYSQL");
    m_db.setHostName(hostName);
    m_db.setDatabaseName(dbName);
    m_db.setUserName(userName);
    m_db.setPassword(userPassword);

    if (m_db.open()) {
        qDebug() << "Connected to database";
    }
    else {
        qDebug() << "Error occured in connection to database";
        return false;
    }
    return true;
}

bool DataBaseAccessor::addUser(QString &userLogin, QString &userPassword, USER_RIGHT right)
{
    QSqlQuery query(m_db);
    m_db.transaction();
    query.prepare("SELECT id FROM users WHERE login = :login");
    query.bindValue(":login", userLogin);
    query.exec();
    if (query.next()) {
        m_db.commit();
        qDebug() << query.value(0);
        return false;
    }
    query.clear();
    query.prepare("INSERT INTO users(login, password, user_right) "
                  "VALUES(:login, MD5(:password), :user_right)");
    query.bindValue(":login", userLogin);
    query.bindValue(":password", userPassword);
    query.bindValue(":user_right", right);
    qDebug() << query.lastQuery();
    bool ok = query.exec();
    m_db.commit();
    if(ok) {
        qDebug() << "New login was added";
    }
    else {
        qDebug() << "Shit!Oo" << query.lastError().text();
        return false;
    }
    return true;
}

void DataBaseAccessor::getList()
{
    //QSqlQuery query(m_db);
    //query.prepare("SELECT")
}

unsigned long long DataBaseAccessor::loginUser(QString &userLogin,
                                               QString &userPassword)
{
    QSqlQuery query(m_db);
    query.prepare("SELECT id FROM users " \
                  "WHERE login = :login AND password = MD5(:password)");
    query.bindValue(":login", userLogin);
    query.bindValue(":password", userPassword);
    query.exec();
    if (query.next()) {
        return query.value(0).toULongLong();
    }
    return 0;
}

void DataBaseAccessor::execQuery(QString &query,  qint32 socket)
{
   // QSqlQuery query(m_db);

   // emit callback(query, socket);
}

DataBaseAccessor::DataBaseAccessor()
{
}


